package com.stylefeng.guns.core.util;

import java.io.IOException;

import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.exception.GunsExceptionEnum;

/**
 * 可扩展
 * 只做json的支持
 *
 * @author carloszhang
 */
@Slf4j
@Component("okHttpTool")
public class OkHttpTool {
	

    private static final String CHARSET_UTF8 = "UTF-8";

    @Autowired
    @Qualifier("buildOkHttpClient")
    private OkHttpClient buildOkHttpClient;

    public String sendGet(String url) {
        OkHttpClient okHttpClient = buildOkHttpClient.newBuilder().build();
        Request.Builder requestBuilder = new Request.Builder().url(url);

        Response response=null;
        String responeContent = StringUtils.EMPTY;
        try {
           response = okHttpClient.newCall(requestBuilder.build()).execute();
           responeContent=responeContent(response);
        }catch (Exception e){
//            log.error("okHttpTool sendGet error",e);
            throw new GunsException(GunsExceptionEnum.EXTERNAL_ERROR);
        }finally {
            if (response!=null){
                response.close();
            }
        }
        return responeContent;
    }


    /**
     *构造返回结果
     */
    private String responeContent(Response response, String contentType) throws IOException {
        String responeContent = StringUtils.EMPTY;
        if (response.isSuccessful()) {
            responeContent = IOUtils.toString(response.body().bytes(), contentType);
        }
        return responeContent;
    }


    private String responeContent(Response response) throws UnsupportedOperationException, IOException {
        return responeContent(response, CHARSET_UTF8);
    }

}
